<template>
	<view>
		<view class="feedback-title">
			意见反馈：
		</view>
		<view class="feedback-content">
			<textarea class="feedback-textarea" v-model="content" placeholder="请输入您要反馈的问题" />
		</view>

		<view class="feedback-title">
			反馈图片：
		</view>

		<view class="feedback-image-box">
			<view class="feedback-image-item" v-for="(item,index) in imageList" :key="index">
				<view @click="deleteImage(index)" class="close-icon">
					<uni-icons type="closeempty" size="18" color="#fff"></uni-icons>
				</view>
				<view class="image-box">
					<image :src="item.url" mode="aspectFill"></image>
				</view>
			</view>
			<!-- 添加图片的icon -->
			<view v-if="imageList.length < 5" class="feedback-image-item" @click="_addImage">
				<view class="image-box">
					<uni-icons type="plusempty" size="50" color="#eee"></uni-icons>
				</view>
			</view>
		</view>

		<button type="warn" class="feedback-button" @click="_submitFeedback">提交反馈意见</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				content: '',
				imageList: []
			}
		},
		methods: {
			// 添加图片
			async _addImage() {
				const count =  5 - this.imageList.length
				uni.chooseImage({
					count,
					success:(res)=> {
						const tempFilePaths = res.tempFilePaths
						tempFilePaths.forEach((url,index)=>{
							if(index < count) {
								this.imageList.push({
									url,
									// #ifdef H5
									name:res.tempFiles[index].name,
									// #endif
									// #ifndef H5
									name:Date.now().toString() + url.substr(url.lastIndexOf('.')), // 时间戳+ 获取扩展名
									// #endif
								})
							}
						})
					}
				})
			},
			// 发送意见反馈的内容
			async _submitFeedback() {
				if(this.content) {
					uni.showLoading({})
					const feedbackImageList = await Promise.all(this.getFiledId())
					uni.hideLoading()
					const {msg} = await this.$http.update_feedback({
						content: this.content, 
						feedbackImageList, 
						userId: this.userInfo._id,
						})
					 uni.showToast({
					        title: msg,
							icon:'none'
					    })
					setTimeout(() => {
					    uni.switchTab({
					        url: '/pages/self/index'
					    })
					}, 1500)
				} else {
					uni.showModal({
						title:'请填写意见信息',
						showCancel: false
					})
				}
			},
			deleteImage(index) {
				// 删除图片
				this.imageList.splice(index,1)
			},
			getFiledId() {
				// 获取上传的图片地址
				return this.imageList.map(item =>{
					return new Promise(async (resolve,reject)=>{
						const result = await uniCloud.uploadFile({
							filePath:item.url,
							cloudPath:item.name
						})
						resolve(result.fileID)
					})
				})
			},
			// 生成唯一id
			generatedId(num) {
				return Number(Math.random().toString().substr(3,num) + Date.now()).toString(36)
			}
		}
	}
</script>

<style lang="scss">
	@import './css/feedback.scss'
</style>
